package com.cdn.dispatch.controller;

import com.alibaba.fastjson.JSONObject;
import com.cdn.common.core.domain.R;
import com.cdn.common.redis.service.RedisService;
import com.cdn.nodes.api.RemoteNodeService;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/dispatch")
public class RepDispatchController {

    @Resource
    private RemoteNodeService remoteNodeService;

    @Resource
    private RedisService redisService;
    // 测试节点服务器地址
//    private static final String SELECTED_NODE = "node1.cdnk.xyz";

    //  处理请求，返回选定的节点的302重定向响应
    @GetMapping("/redirect")
    public ResponseEntity<Void> redirectNode(@RequestParam String path) {
        try {
            // 从 Redis 获取所有节点的 nodeId 集合
            Set<String> nodeIds = redisService.getSet("nodeIds");
            if (nodeIds == null || nodeIds.isEmpty()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }

            // 根据节点ID逐一从Redis取出节点数据
            List<JSONObject> nodeDataList = new ArrayList<>();
            for (String nodeId : nodeIds) {
                String key = "node:" + nodeId;
                Object nodeData = redisService.getCacheObject(key);
                if (nodeData != null) {
                    nodeDataList.add((JSONObject) nodeData);
                }
            }

            // 如果没有节点数据，返回 404
            if (nodeDataList.isEmpty()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }

            // 筛选最优节点
            JSONObject bestNode = selectBestNode(nodeDataList);

            // 获取最佳节点的 nodeId
            String selectedNodeId = bestNode.getString("nodeId");

            // 获取最佳节点的线路信息
            R<String> url = remoteNodeService.getDnsLineByNodeId(Long.valueOf(selectedNodeId));

            System.out.println(url);

            // 拼接重定向URL
            String redirectUrl = "http://" + url + path;

            // 返回 302 重定向响应
            return ResponseEntity.status(HttpStatus.FOUND)
                    .header("Location", redirectUrl)
                    .build();

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据规则筛选最优节点
     * @param nodeDataList 所有节点数据列表
     * @return 最优节点
     */
    private JSONObject selectBestNode(List<JSONObject> nodeDataList) {
        JSONObject bestNode = null;

        // 设置初始的筛选条件（如最小的负载和流量）
        BigDecimal minLoad = BigDecimal.valueOf(Double.MAX_VALUE);
        Long minBandwidth = Long.MAX_VALUE;
        Integer minConnections = Integer.MAX_VALUE;

        // 遍历所有节点数据并根据指定的条件选择最优节点
        for (JSONObject node : nodeDataList) {
            Long downstreamBandwidth = node.getLong("downstreamBandwidth");
            Integer connections = node.getInteger("connections");
            BigDecimal load = node.getBigDecimal("load");

            // 设置筛选条件：比如负载最小且带宽大，连接数少的节点最优
            if (load != null && load.compareTo(minLoad) < 0 && downstreamBandwidth != null && downstreamBandwidth < minBandwidth && connections != null && connections < minConnections) {
                bestNode = node;
                minLoad = load;
                minBandwidth = downstreamBandwidth;
                minConnections = connections;
            }
        }

        // 返回最优节点
        return bestNode;
    }

}
